<?php
/**
 * 初始化工作
 *
 * PHP Version 5.6
 *
 * @category PHP
 * @package  TelegramPostBot
 * @author   ctwj <908504609@qq.com>
 * @license  MIT https://github.com/ctwj/wechat_search/blob/master/LICENSE
 * @link     https://github.com/ctwj/wechat_search/
 * @date     2018-05-13 22:56:47
 * @modifyby ctwj
 */

use Telegram\TPLogger;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Telegram\Bot\HttpClients\GuzzleHttpClient;
use GuzzleHttp\Client;

/**
 * Init path define
 */
define('SRC_ROOT', dirname(__FILE__));
define('PROJECT_ROOT', dirname(SRC_ROOT));
define('DS', DIRECTORY_SEPARATOR);
define('BIN_ROOT', SRC_ROOT . DS . 'bin');
define('LOG_PATH', SRC_ROOT . DS . 'log');
define('CACHE_PATH', SRC_ROOT . DS . 'cache');
define('PLUGINS_PATH', SRC_ROOT . DS . 'Telegram' . DS . 'Plugins');
define('CLI', preg_match("/cli/i", php_sapi_name()) ? true : false);


if (!file_exists(LOG_PATH)) {
    mkdir(LOG_PATH);
}
if (!file_exists(CACHE_PATH)) {
    mkdir(CACHE_PATH);
}

/**
 * Set env language
 */
setlocale(LC_ALL, 'en_US.UTF-8');
putenv('LC_ALL=en_US.UTF-8');
date_default_timezone_set('PRC');   //北京时间

/**
 * Load library
 */
require_once PROJECT_ROOT . DS . 'vendor/autoload.php';

/**
 * Load Config
 */
$dotenv = new Dotenv\Dotenv(SRC_ROOT);
$dotenv->overload();
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS', 'BOT_API_KEY'])->notEmpty();
$dotenv->required('DB_PORT')->isInteger();
$dotenv->required('DEBUG')->isBoolean();
$dotenv->required('POST_NUMBER_EACH_TIMES')->isInteger();

/**
 * Debug
 */
$tpb_debug = getenv('DEBUG');
if ($tpb_debug) {
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);
}

/**
 * DI 容器, logger, database
 */
$container = new Pimple\Container();
$container['logger'] = function ($c) {
    return new Telegram\TPLogger(LOG_PATH, getenv('DEBUG'));
};
$container['database'] = function ($c) {
    return new Medoo\Medoo(
        [
            'database_type' => getenv('DATABASE_TYPE'),
            'database_name' => getenv('DB_NAME'),
            'server'        => getenv('DB_HOST'),
            'username'      => getenv('DB_USER'),
            'password'      => getenv('DB_PASS'),
            'port'          => getenv('DB_PORT'),
            'prefix'        => getenv('DB_PREFIX'),
            'loggging'      => !getenv('DEBUG'),
            'charset'       => 'utf8'
        ]
    );
};

/**
 * 注册数据库model
 */
$container['userModel'] = function ($c) {
    return new \Telegram\Data\UserModel($c);
};
$container['messageModel'] = function ($c) {
    return new \Telegram\Data\MessageModel($c);
};
$container['bodyModel'] = function ($c) {
    return new \Telegram\Data\BodyModel($c);
};
$container['resourceModel'] = function ($c) {
    return new \Telegram\Data\ResourceModel($c);
};
$container['destinationModel'] = function ($c) {
    return new \Telegram\Data\DestinationModel($c);
};

$container['telegram'] = function ($c) {
    $bot_api_key    = getenv('BOT_API_KEY');
    if (empty($bot_api_key)) {
        $c['logger']->error('Must Set The Telegram bot_api_key');
        exit(1);
    }
    $proxy = getenv('PROXY');
    try {
        if (!$proxy) {
            $telegram = new Telegram\Bot\Api($bot_api_key);
        } else {
            // $client = new GuzzleHttpClient(new Client(['proxy' => $proxy, 'debug' => getenv('DEBUG')]));
            $client = new GuzzleHttpClient(new Client(['proxy' => $proxy]));
            $telegram = new Telegram\Bot\Api($bot_api_key, false, $client);
        }
    } catch (\Exception $e) {
        $c['logger']->error('Initaily Telegram Bot Fail', $e);
        exit(1);
    }
    return $telegram;
};

/**
 * 注册插件
 */
$container['plugindispatcher'] = function ($c) {
    $dispatcher = new EventDispatcher();
    Telegram\Plugins::registerPlugin($dispatcher);
    return $dispatcher;
};


/**
 * 获取默认UserAgent
 *
 * @return string
 */
function getUserAgent()
{
    $useragent = getenv('USER_AGENT');
    if (empty($useragent)) {
        $useragent = 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11';
    }
    return $useragent;
}


/**
 * 获取服务容器
 *
 * @return Container
 */
function getContainer()
{
    global $container;
    return $container;
}
/**
 * 获取服务
 *
 * @param [type] $service 服务名字
 *
 * @return Service
 */
function getService($service)
{
    return getContainer()[$service];
}

/**
 * 获取时间 对象
 *
 * @param string $str 时间字符串，当不传入参数，默认为当前时间
 *
 * @return \Datetime
 */
function getTime($str = '')
{
    if ($str !== '') {
        return new \DateTime($str, new \DateTimeZone('PRC'));
    }
    return new \DateTime(date('Y-m-d H:i:s'), new \DateTimeZone('PRC'));
}

/**
 * 系统级错误捕捉，因为多数情况下，任务是命令行执行的，如果有异常看不到，需要记录处理
 */
// register_shutdown_function(['Telegram\Utils\ErrorHandler', 'shutdown']);
/**
 * 异常捕捉，未捕捉的异常也会导致程序终止，需要记录处理
 */
//set_exception_handler(['Telegram\Utils\ErrorHandler', 'exceptionHandler']);
